package com.itrh.auth.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.itrh.auth.service.IPermissionService;
import com.itrh.base.annotation.AuthPermission;
import com.itrh.org.util.LoginMap;
import com.itrh.org.util.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * ClassName: LoginInterceptor
 *
 * @author XHU_WHY
 * @version V1.0
 * @since 2024/4/8 14:20
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private IPermissionService permissionService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        // 获取请求头中的token 名字为TOKEN
        String token = request.getHeader("TOKEN");
        if (token == null || token.equals("")) {
            Result error = Result.error("NOT_LOGIN");
            response.getWriter().write(JSONObject.toJSONString(error));
            return false;
        } else {
            // 判断token是否在Map中
            if (!LoginMap.getLoginMap().containsKey(token)) {
                Result error = Result.error("NOT_LOGIN");
                response.getWriter().write(JSONObject.toJSONString(error));
                return false;
            }
        }
        // 校验权限
        // 获取访问的方法
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        if (handlerMethod.getMethodAnnotation(AuthPermission.class) != null) {
            List<String> auths = permissionService.getPermissionByEmpId(LoginMap.getEmployee(token).getId());
            // 判断当前登录用户的权限是否包含访问的方法的权限
            // 类名
            String className = handlerMethod.getBeanType().getSimpleName();
            // 方法名
            String methodName = handlerMethod.getMethod().getName();
            if (!auths.contains(className + ":" + methodName)) {
                Result error = Result.error("NO_AUTH");
                response.getWriter().write(JSONObject.toJSONString(error));
                return false;
            }
        }
        return true;
    }
}
